Page({
  data: {
    addressId: null,
    formData: {
      name: '',
      phone: '',
      province: '广东省',
      city: '深圳市',
      district: '南山区',
      detail: '',
      isDefault: false
    }
  },
  
  onLoad(options) {
    if (options.id) {
      // 编辑模式，加载地址数据
      this.data.addressId = options.id
      this.loadAddressData(options.id)
    }
  },
  
  loadAddressData(id) {
    // 模拟从地址列表加载对应ID的地址数据
    const addressId = parseInt(id)
    
    // 模拟地址数据列表
    const mockAddresses = [
      {
        id: 1,
        name: '张三',
        phone: '13800138000',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detail: '科技园南区',
        isDefault: true
      },
      {
        id: 2,
        name: '李四',
        phone: '13900139000',
        province: '北京市',
        city: '北京市',
        district: '朝阳区',
        detail: '国贸大厦A座',
        isDefault: false
      }
    ]
    
    // 根据ID查找对应的地址数据
    const addressData = mockAddresses.find(addr => addr.id === addressId) || {
      id: addressId,
      name: '',
      phone: '',
      province: '广东省',
      city: '深圳市',
      district: '南山区',
      detail: '',
      isDefault: false
    }
    
    this.setData({
      formData: addressData
    })
  },
  
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value
    })
  },
  
  onSwitchChange(e) {
    this.setData({
      'formData.isDefault': e.detail.value
    })
  },
  
  onRegionChange(e) {
    const [province, city, district] = e.detail.value
    this.setData({
      'formData.province': province,
      'formData.city': city,
      'formData.district': district
    })
  },
  
  saveAddress() {
    const { name, phone, province, city, district, detail } = this.data.formData
    
    if (!name || !phone || !detail) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return
    }
    
    // 模拟保存地址
    wx.showToast({
      title: this.data.addressId ? '地址修改成功' : '地址添加成功',
      icon: 'success',
      success: () => {
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      }
    })
  },
  
  deleteAddress() {
    if (!this.data.addressId) return
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个地址吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showToast({
            title: '地址删除成功',
            icon: 'success',
            success: () => {
              setTimeout(() => {
                wx.navigateBack()
              }, 1500)
            }
          })
        }
      }
    })
  }
})